//
// Created by whg on 2025-06-01.
//

#include "arrayList.hpp"
#include <stdio.h>

template <typename T>
ArrayList<T>::ArrayList(int capacity) {
    _capacity = capacity;
    _length = 0;
    _array = new T[capacity];
}

template<typename T>
void ArrayList<T>::add(T t) {
    if(_length >= _capacity){
        expand();
    }

    _array[_length++] = t;
}

template<typename T>
void ArrayList<T>::insert(int index, T t) {
    add(nullptr);

    for(int i=_length;i>index;i--){
        _array[i] = _array[i-1];
    }

    _array[index] = t;
}

template<typename T>
void ArrayList<T>::expand() {
    const int new_capacity = _capacity << 1;  // 乘以2的扩容
    T* new_array = new T[new_capacity];
    for(int i=0;i<_length;i++){
        new_array[i] = _array[i];
    }
    delete[] _array;
    _array = new_array;

    _capacity = new_capacity;
    printf("expand arrayList capacity to %d, length is %d\n", _capacity, _length);
}

template<typename T>
T ArrayList<T>::get(int index) {
    return _array[index];
}

template<typename T>
void ArrayList<T>::set(int index, T t) {
    if(_length <= index){
        _length = index + 1;
    }

    while(_length > _capacity){
        expand();
    }

    _array[index] = t;
}

template<typename T>
int ArrayList<T>::capacity() {
    return _capacity;
}

template<typename T>
int ArrayList<T>::length() {
    return _length;
}

template<typename T>
void ArrayList<T>::push(T t) {
    add(t);
}

template<typename T>
T ArrayList<T>::pop() {
    return _array[--_length];
}

// 为了避免链接器报错找不到符号，下面是强制编译器对模板类进行实例化
class PyObject;
template class ArrayList<PyObject*>;

class PyString;
template class ArrayList<PyString*>;